<!--
    group: 发票管理
    name: 开票列表
    item: 邀请验证---（展示业务说明书签署链接和二维码弹层）
-->
<template>
  <a-modal
    :width="700"
    :footer="null"
    v-model="invitationShow"
    :destroyOnClose="true"
    :maskClosable="false"
    @cancel="handleCancle"
  >
    <h3>邀请验证</h3>
    <div class="main">
      <div class="boxLeft">
        <span class="title">短信邀请法人完成《业务说明书》签署</span>

        <div class="preview">
          <p>
            尊敬的"{{ inContent.taxTitle }}"，您有{{ text }}信息待确认，点击以下链接确认信息并完成验证。
            <a :href="shortChain" target="_blank">{{ shortChain }}</a>
          </p>
        </div>

        <p class="tips" v-if="textShow">发送成功</p>
        <a-button type="primary" @click="send" :disabled="disabledCodeBtn">{{ codeText }}</a-button>
      </div>
      <div class="boxRight">
        <span class="title">法人扫码完成《业务说明书》签署</span>

        <a-spin :spinning="spinning">
          <div class="code" style="flex-direction: column;">
            <!-- <span style="    font-weight: bold; color: gray;">业务核验</span> -->
            <img class="img" :src="codeUrl" alt="二维码图片">
          </div>
        </a-spin>

        <p class="tips" v-if="codeShow">下载成功</p>
        <a-button type="primary" @click="upDown">下载二维码</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import {
  getInvoiceSignUrl, getTaxInvoiceCheckSendSms,getInvoiceBaseUrl,
  getInvoiceReturnSignUrl,getTaxReturnTicketBatchCheck,
} from '@api/invoiceAdminister'

export default {
  name: 'invitationCode',
  props: ['invitationShow','inContent','showCodeTitle'],
  data(){
    return{
      text: '开票',
      shortChain: null,  //短链
      codeText: '发送短信',
      disabledCodeBtn: false,
      textShow: false, //发送成功提示

      spinning: true,
      codeUrl: null,  //二维码
      codeShow: false,  //复制成功提示
    }
  },
  watch:{
    inContent(val){
      // console.log(val)
      if (val){
        //status 1 新开票 2 退票 3 退票-错票
        // val.status == 2 ? this.text = '退票' : this.text = '开票';
        const setTextStr = (status_)=>{
          const actionList = {
            '1':()=>{ this.text = '开票' },
            '2':()=>{ this.text = '退票' },
            '3':()=>{ this.text = '开票' },
          }
          actionList[status_] && actionList[status_]()
        }
        setTextStr(val.status)

        //104 开票核验 202 退票核验
        if (val.id){
          if (val.bizStatus == 104 || val.bizStatus == 202){
            this.getDetails(val.id);
          }
        }
      }
    }
  },
  methods:{
    //发送短信
    send(){
      let ids = [];
      ids.push(this.inContent.id)
      let params = {};
      params.data = {
        ids: ids,
      }

      //status 1 新开票 2 退票 3 退票-错票
      if (this.inContent.status == 2){
        getTaxReturnTicketBatchCheck(params).then(res => {
          if (res.success) {
            // this.$message.success('发送成功');
            this.textShow = true;
            this.countDown(60);
          }else{
            this.$message.warning(res.message);
          }
        })
      }else{
        //请求接口
        getTaxInvoiceCheckSendSms(params).then(res => {
          if (res.success) {
            // this.$message.success('发送成功');
            this.textShow = true;
            this.countDown(60);
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    },
    newUpDown(){
      // const imgElement = document.getElementById('imgBox')
      // const range = document.createRange();
      // range.selectNode(imgElement);
      // window.getSelection().removeAllRanges();
      // window.getSelection().addRange(range);

      // const success = document.execCommand('copy');
      // if (success) {
      //   console.log('图片复制成功');
      // } else {
      //   console.log('图片复制失败');
      // }



      var bstr = atob(this.codeUrl.split(',')[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
          // var blob = new Blob([u8arr]);
      navigator.clipboard.write([
        new ClipboardItem({
          'image/png': new Blob([u8arr], { type: 'image/png' })
        })
      ]).then(function() {
        console.log('图片复制成功');
      }).catch(function(err) {
        console.error('图片复制失败: ', err);
      });



      // const inputEle = document.createElement('input');
      // inputEle.setAttribute('readonly', true);
      // inputEle.setAttribute('value', this.codeUrl);
      // document.body.appendChild(inputEle);
      // inputEle.select();
      // const isCopied = document.execCommand('copy');
      // if (isCopied) {
      //   console.log('Base64 图片复制成功');
      // } else {
      //   console.log('Base64 图片复制失败');
      // }
      // document.body.removeChild(inputEle);
    },
    //复制二维码
    upDown(){
      // this.newUpDown()
      if (this.codeUrl){
        const imgUrl = this.codeUrl;
        // 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          var bstr = atob(imgUrl.split(',')[1]);
          var n = bstr.length;
          var u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          var blob = new Blob([u8arr]);
          window.navigator.msSaveOrOpenBlob(blob, 'code' + '.' + 'png');
        } else {
          // 这里就按照chrome等新版浏览器来处理
          const a = document.createElement('a');
          a.href = imgUrl;
          a.setAttribute('download', 'code');
          a.click();
        }

        // this.$message.success('复制成功');
        this.codeShow = true;
      }
    },
    //获取短链
    getDetails(id){
      let ids = [];
      ids.push(id)
      let params = {};
      params.data = {
        ids: ids,
      }

      //status 1 新开票 2 退票 3 退票-错票
      if (this.inContent.status == 2){
        getInvoiceReturnSignUrl(params).then(res => {
          if (res.success) {
            //获取短链
            this.shortChain = res.result;
            this.getInvoiceUrl(this.shortChain);
          }else{
            this.$message.warning(res.message);
          }
        })
      }else{
        getInvoiceSignUrl(params).then(res => {
          if (res.success) {
            //获取短链
            this.shortChain = res.result;
            this.getInvoiceUrl(this.shortChain);
          }else{
            this.$message.warning(res.message);
          }
        })
      }
    },
    //获取图片Base
    getInvoiceUrl(url){
      let params = {};
      params.url = url;
      params.key = '';
      if(this.showCodeTitle && this.showCodeTitle){
        params.key = '业务核验';
      }
      getInvoiceBaseUrl(params).then(res => {
        if (res.status == 0) {
          this.codeUrl = res.value;
          this.spinning = false;
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //关闭
    handleCancle(){
      this.$emit('handleCodeFather');
    },
    // 倒计时方法
    countDown(time) {
      if (time === 0) {
        this.disabledCodeBtn = false;
        this.textShow = false;
        this.codeText = "重新发送";
        return;
      } else {
        this.disabledCodeBtn = true;
        this.codeText = "(" + time + "秒后)重新发送";
        time--;
      }
      setTimeout(() => {
        this.countDown(time);
      }, 1000);
    },
  }
}
</script>

<style scoped lang="less">
h3{
  font-weight: bold;
}
.main{
  width: 100%;
  padding: 15px 5px 10px 5px;
  box-sizing: border-box;
  display: flex;
  .title{
    font-weight: bold;
    color: #333333;
  }
  .boxLeft{
    width: 55%;
    box-sizing: border-box;
    padding: 0 20px 0 10px;
    .preview{
      width: 100%;
      box-sizing: border-box;
      border-radius: 5px;
      min-height: 120px;
      border: 2px solid #e8e8e8;
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      p{
        width: 90%;
        margin-bottom: 0px;
        a{
          display: inline-block;
        }
      }
    }
    .tips{
      background: rgba(43, 162, 69, 0.38);
      border-radius: 20px;
      text-align: center;
      color: #FFFFFF;
    }
    .ant-btn-primary{
      margin-left: 110px;
    }
  }
  .boxRight{
    width: 45%;
    border-left: 1px solid #e8e8e8;
    padding: 0 10px 0 20px;
    display: flex;
    justify-content: flex-start;
    align-items:center;
    flex-direction: column;
    .code{
      width: 100%;
      min-height: 120px;
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: center;
      .img{
        width: 110px;
        height: 110px;
      }
    }
    .tips{
      background: rgba(43, 162, 69, 0.38);
      border-radius: 20px;
      text-align: center;
      color: #FFFFFF;
    }
    .ant-btn-primary{
      // margin-left: 80px;
    }
  }
}
</style>
